package com.tanhua.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.Intercepter.UserHolder;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mogo.Comment;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class CommentsService {
    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    /**
     * 发布评论
     *
     * @param movementId 动态id
     * @param comment    评论内容
     */
    public void Release(String movementId, String comment) {
        Comment comment1 = new Comment();
        comment1.setPublishId(new ObjectId(movementId));
        comment1.setCommentType(CommentType.COMMENT.getType());
        comment1.setContent(comment);
        Long id = UserHolder.getId();
        comment1.setUserId(id);
        comment1.setCreated(System.currentTimeMillis());
        //保存评论
        Integer count = commentApi.Release(comment1);

    }

    /**
     * 查询评论列表
     *
     * @param page
     * @param pagesize
     * @param movementId
     * @return
     */
    public PageResult Lookup(Integer page, Integer pagesize, String movementId) {
        //调用api查询评论列表
        List<Comment> commentList = commentApi.Lookup(page, pagesize, movementId,CommentType.COMMENT);
        //非空判断
        if (CollUtil.isEmpty(commentList)) {
            return new PageResult();
        }
        //提取所有用户id列表
        List<Long> userIds = CollUtil.getFieldValues(commentList, "userId", Long.class);
        //查询用户详细信息
        Map<Long, UserInfo> map = userInfoApi.MakeFriends(userIds, null);
        //封装vo集合
        List<CommentVo> vos = new ArrayList<>();
        for (Comment comment : commentList) {
            UserInfo userInfo = map.get(comment.getUserId());
            if (userInfo != null) {
                CommentVo vo = CommentVo.init(userInfo, comment);
                vos.add(vo);

            }
        }
        PageResult pr = new PageResult(page,pagesize,0,vos);
        return pr;
    }
}
